package com.wontube.smr.web.utils;

import java.io.File;
import java.io.IOException;

import com.wontube.client.extension.utils.FileUtils;

/**
 * @author tanggf(2012-8-31)
 *
 */
public class CompressUtil {
	public static void main(String[] args) throws Exception{
		compressJS();
	}
	
	public static void compressJS() throws IOException{		
		String dir = System.getProperty("user.dir");
		String jsDir = FileUtils.combinePath(dir, "src", "main", "webapp", "js");
		File pluginDir = new File(FileUtils.combinePath(jsDir, "plugin"));
		File[] pluginFiles = pluginDir.listFiles();
		StringBuilder sb = new StringBuilder();
		sb.append("//version 1.4 from WonTube Studio\n");
		//ga.js, utils.js, social/fb-sdk.js
		sb.append(trimFromFile(new File(FileUtils.combinePath(jsDir, "social", "fb-sdk.js")))).append("\n");
		//sb.append(trimFromFile(new File(FileUtils.combinePath(jsDir, "social", "ga.js")))).append("\n");
		sb.append(trimFromFile(new File(FileUtils.combinePath(jsDir, "utils.js")))).append("\n");		
		
		//plugin
		for (File file : pluginFiles) {
			sb.append("//" + file.getName() + "\n");
			String content = trimFromFile(file);
			sb.append(content).append("\n");
		}
		
		//main.js
		//sb.append(trimFromFile(new File(FileUtils.combinePath(jsDir, "main.js")))).append("\n");
		
		File all = new File(FileUtils.combinePath(jsDir, "all.js"));
		
		
		FileUtils.saveToFile(sb.toString(), all);
	}
	
	private static String trimFromFile(File file) throws IOException{		
		String content = FileUtils.readAllText(file);		
		//去掉 //注释
		content = content.replaceAll("(?m)(^\\s*|[,;\\(\\)\\{\\}]\\s*)//.*$", "$1");			
		//去掉 行首的/**/注释
		content = content.replaceAll("(?s)(^|\\n+)\\s*/\\*.*?\\*/", "");	
		//去掉空行
		content = content.replaceAll("[\\r\\n]+", "\n");		
		//去掉转行,tab
		content = content.replaceAll("[\\r\\n\\t]", "");
				
		return content;
	}
}
